package com.zhdl.common.service;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.JWTVerifier;
import com.zhdl.common.interceptor.MyAssert;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;

import static com.zhdl.common.constant.HttpCodeEnum.UNAUTHORIZED;

@Slf4j
@Service
public class TokenService {

    @Value("${token.salt:*test*@}")
    private String salt;

    @Value("${token.validityTime:72000000}")
    private Long validityTime;


    public String createToken(String userId) {
        return JWT.create()
                .withAudience(userId)
                .withIssuedAt(new Date())
                .withExpiresAt(new Date(System.currentTimeMillis() + validityTime))
                .sign(Algorithm.HMAC256(salt.concat(userId)));
    }


    private String getValue(String token, int index) {
        return JWT.decode(token).getAudience().get(index);
    }

    /**
     * 校验token
     *
     * @param userId
     * @return
     */
    public JWTVerifier verifier(String userId) {
        MyAssert.isBlank(userId, UNAUTHORIZED.getCode(), "token 认证失败");
        return JWT.require(Algorithm.HMAC256(salt.concat(userId))).build();
    }

    public String getUserId(String token) {
        return getValue(token, 0);
    }

    public long getValidityTime() {
        return validityTime;
    }
}
